#include <atomic>
#include <chrono>
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>
#include <vector>

// 任务类型
enum class TaskType { INTERACTIVE,
    BATCH,
    REALTIME };

// 模拟任务
struct Task {
    int id;
    TaskType type;
    int burst_time; // 模拟执行时间 (ms)
    int priority; // 优先级（动态变化）
    int waited_time = 0; // 等待时间（用于动态调节优先级）

    // 自定义比较函数 (priority越高，排在队列前面)
    bool operator<(const Task& other) const
    {
        return priority < other.priority;
    }
};

// 全局任务队列
std::priority_queue<Task> task_queue;
std::mutex queue_mutex;
std::condition_variable cv;
std::atomic<bool> running(true);

// 调度器线程
void scheduler(int cpu_id)
{
    while (running) {
        Task current;
        {
            std::unique_lock<std::mutex> lock(queue_mutex);
            if (task_queue.empty()) {
                cv.wait_for(lock, std::chrono::milliseconds(100));
                continue;
            }
            current = task_queue.top();
            task_queue.pop();
        }

        // 模拟执行时间片 (50ms)
        int time_slice = 50;
        int exec_time = std::min(time_slice, current.burst_time);
        std::cout << "[CPU " << cpu_id << "] Running task " << current.id
                  << " (priority=" << current.priority
                  << ", type=" << (int)current.type << ") for "
                  << exec_time << "ms\n";

        std::this_thread::sleep_for(std::chrono::milliseconds(exec_time));
        current.burst_time -= exec_time;

        if (current.burst_time > 0) {
            // 动态调整优先级 (CFS思想: 等待太久就升优先级)
            current.priority += 1;
            {
                std::lock_guard<std::mutex> lock(queue_mutex);
                task_queue.push(current);
            }
            cv.notify_one();
        }
    }
}

// 模拟任务创建
void submit_tasks()
{
    std::vector<Task> tasks = {
        { 1, TaskType::INTERACTIVE, 120, 10 }, // 高优先级，交互任务
        { 2, TaskType::BATCH, 300, 5 }, // 低优先级，脚本型
        { 3, TaskType::REALTIME, 80, 50 }, // 最高优先级，实时任务
        { 4, TaskType::BATCH, 200, 5 },
        { 5, TaskType::INTERACTIVE, 150, 15 }
    };

    {
        std::lock_guard<std::mutex> lock(queue_mutex);
        for (auto& t : tasks) {
            task_queue.push(t);
        }
    }
    cv.notify_all();
}

int main()
{
    // 启动两个调度线程 (模拟双核 CPU)
    std::thread cpu1(scheduler, 0);
    std::thread cpu2(scheduler, 1);

    // 提交任务
    submit_tasks();

    // 运行 2 秒后停止
    std::this_thread::sleep_for(std::chrono::seconds(2));
    running = false;
    cv.notify_all();

    cpu1.join();
    cpu2.join();
    return 0;
}
